package com.alfayun.fiscalriskanalysis.util;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import org.springframework.lang.NonNull;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

@Converter
public class IdsConverter implements AttributeConverter<List<Integer>, String> {

	@NonNull
	@Override
	public String convertToDatabaseColumn(List<Integer> ids) {
		return joinList(ids);
	}

	@NonNull
	@Override
	public List<Integer> convertToEntityAttribute(String ids) {
		return splitString(ids);
	}
	
	public static String joinList(List<Integer> ids) {
		if(ids != null) {
			return Joiner.on(',').join(ids);
		}
		return null;
	}

	public static List<Integer> splitString(String ids) {
		if(ids != null) {
			return new ArrayList<>(Splitter.on(',').omitEmptyStrings().trimResults()
					.splitToList(ids).stream().map(it -> Integer.valueOf(it)).collect(Collectors.toList()));
		}
		return null;
	}

}
